(function () {
  // 完成横幅区的图片切换
  // 横幅区数据
  var datas = [
    {
      img: "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/15c05b32cf948b594477dfc3eb69fb69.jpg?w=2452&h=920",
      link: "https://www.mi.com/mi11le-5g-ne",
    },
    {
      img: "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/a532e33470d046b3f044d5ea49fc5e9e.png?thumb=1&w=2452&h=920&f=webp&q=90",
      link: "https://www.mi.com/xiaomipad5",
    },
    {
      img: "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/918820682e4a490221cfd92b24c14b86.jpg?thumb=1&w=2452&h=920&f=webp&q=90",
      link: "https://www.mi.com/a/h/22033.html?sign=b60a6ca9167bce2d1ed8ee319cf83c75",
    },
    {
      img: "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/af7be8f65065f405f57f46a02731f78d.jpg?thumb=1&w=2452&h=920&f=webp&q=90",
      link: "https://www.mi.com/a/h/22812.html?sign=aab397a7ecf2ae4c1765e9d11fdccca6",
    },
  ];

  const bannerEl = document.querySelector(".banner.container");
  const bannerDots = document.querySelector(".banner-dots");
  /**
   * 初始化
   */
  function init() {
    datas.forEach((_item) => {
      bannerDots.innerHTML += `<span class="fl"></span>`;
    });
  }

  init();

  /**
   * 将指定下标的数据显示到页面上
   * @param {number} index 要设置的数据索引
   */
  function change(index) {
    const selectedData = datas[index];
    const aEl = bannerEl.querySelector(".banner-cover");
    const imgEl = aEl.querySelector("img");
    aEl.href = selectedData.link;
    imgEl.src = selectedData.img;

    const flEls = Array.prototype.slice.call(
      bannerDots.querySelectorAll(".fl")
    );

    flEls.forEach((item) => {
      item.classList.remove("banner-dots-selected");
    });

    flEls[index].classList.add("banner-dots-selected");
  }

  change(0);

  let curIndex = 0;
  /**
   * 向前一张
   */
  function toPrev() {
    curIndex--;
    if (curIndex < 0) {
      curIndex = datas.length - 1;
    }

    change(curIndex);
  }

  /**
   * 向后一张
   */
  function toNext() {
    curIndex++;
    if (curIndex > datas.length - 1) {
      curIndex = 0;
    }

    change(curIndex);
  }

  const bannerPointerLeftEl = document.querySelector(".banner-pointer-left");
  bannerPointerLeftEl.addEventListener("click", toPrev);

  const bannerPointerRightEl = document.querySelector(".banner-pointer-right");
  bannerPointerRightEl.addEventListener("click", toNext);

  // 小点
  bannerDots.addEventListener("click", function (e) {
    if (e.target.tagName === "SPAN") {
      const spansEl = Array.from(bannerDots.children);
      const index = spansEl.indexOf(e.target);
      curIndex = index; // 记录当前是第几章
      change(index);
    }
  });

  // 自动播放
  let timer = null;
  function start() {
    if (timer) {
      return;
    }

    timer = setInterval(toNext, 1000);
  }

  function stop() {
    clearInterval(timer);
    timer = null;
  }

  start();

  bannerEl.addEventListener("mouseenter", stop);
  bannerEl.addEventListener("mouseleave", start);
})();
